﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Web.Security;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

using PTUDW_CNTN2010_F_CDT.Models;
using PTUDW_CNTN2010_F_CDT.Filters;
using System.Threading;
using Recaptcha;
using Languages;

namespace PTUDW_CNTN2010_F_CDT.Controllers
{
    [LanguageFilter]
    public class AccountController : Controller
    {
        private EcommerceDBContext db = new EcommerceDBContext();

        [HttpGet]
        [LanguageFilter]
        public ActionResult Login()
        {
            var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();
            if (response != null)
            {
                switch (response.Status)
                {

                    case AuthenticationStatus.Authenticated:
                        FormsAuthentication.SetAuthCookie("google", false);
                        return View("LogIn");

                    case AuthenticationStatus.Canceled:
                        ViewBag.Message = "Canceled at provider";
                        return View("LogIn");
                    case AuthenticationStatus.Failed:
                        ViewBag.Message = response.Exception.Message;
                        return View("LogIn");
                }
            }
            return View();
        }

        [HttpPost]
        [LanguageFilter]

        public ActionResult Login(LogInModel account, string returnUrl="../Home/Index")


        {
            if (ModelState.IsValid)
            {
                if (isValidAccount(account.UserName, account.Password))
                {
                    FormsAuthentication.SetAuthCookie(account.UserName, account.RememberMe);
                    if (isAdmin(account.UserName))
                    {
                        HttpCookie cookie = new HttpCookie("ChoOnLineAdmin", account.UserName);
                        Response.Cookies.Add(cookie);
                        return RedirectToAction("Index", "Admin");
                    }
                    return RedirectToAction("LoginState");
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Tai khoan hoac mat khau khong dung");
            }
            ViewBag.loi = Resources.LoginFail;
            return View(account);
        }

        public bool isAdmin(string UserName)
        {
            var customer = db.Customers.Where(c => c.UserName == UserName);
            if (customer.ToList()[0].IsAdmin)
                return true;
            return false;
        }

        public ActionResult LoginState()
        {
            return View();
        }

        public ActionResult Logout()
        {
            var cookie = Request.Cookies["ChoOnLineAdmin"];
            if (cookie != null)
                cookie.Expires = DateTime.Now.AddDays(-1D);

            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult Register()
        {
            ViewBag.Provinces = new SelectList(db.Provinces, "ProvinceId", "ProvinceName");
            return View();
        }


        [HttpPost, RecaptchaControlMvc.CaptchaValidator]
        public ActionResult Register(RegisterModel model, bool captchaValid, string captchaErrorMessage)
        {
            if (!captchaValid)
                ModelState.AddModelError("captcha", captchaErrorMessage);

            if (ModelState.IsValid)
            {
                bool accountExist = db.Customers.Any(c => c.UserName == model.UserName);
                Customer customer = new Customer
                {
                    UserName = model.UserName,
                    Password = model.Password,
                    Email = model.Email,
                    FullName = model.FullName,
                    Address = model.Address,
                    Phone = model.Phone,
                    Sex = model.Sex,
                    IsActive = false,
                    ProvinceId = model.ProvinceId,
                    IsAdmin = false,
                    Level = 0
                };
                if (!accountExist)
                {
                    db.Customers.Add(customer);
                    db.SaveChanges();

                    FormsAuthentication.SetAuthCookie(customer.UserName, false);
                    return RedirectToAction("RegisterSuccessful");
                }
                else
                {
                    ModelState.AddModelError("", "Not " + Languages.Resources.RegisterSuccessful);
                }
            }

            ViewBag.ProvinceId = new SelectList(db.Provinces, "ProvinceId", "ProvinceName");

            return View(model);
        }

        private bool isValidAccount(string userName, string password)
        {
            return db.Customers.Any(c => c.UserName == userName && c.Password == password);
        }

        [ValidateInput(false)]
        public ActionResult Authenticate(string returnUrl)
        {
            var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();
            if (response == null)
            {
                Identifier id;
                string temp = "https://www.google.com/accounts/o8/id";
                if (Identifier.TryParse("https://www.google.com/accounts/o8/id", out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(Identifier.Parse(temp));
                        request.RedirectToProvider();
                        return View();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewBag.Message = ex.Message;
                        return View("Login");
                    }
                }

                ViewBag.Message = "Invalid identifier";
                return View("Login");
            }
            else if (response != null)
            {
                switch (response.Status)
                {

                    case AuthenticationStatus.Authenticated:
                        FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                        return RedirectToAction("Index", "Home");

                    case AuthenticationStatus.Canceled:
                        ViewBag.Message = "Canceled at provider";
                        return RedirectToAction("Login");
                    case AuthenticationStatus.Failed:
                        ViewBag.Message = response.Exception.Message;
                        return RedirectToAction("Login");
                }
            }

            return new EmptyResult();
        }

        public ActionResult RegisterSuccessful()
        {
            return View();
        }

        public JsonResult CheckName(FormCollection form)
        {
            System.Threading.Thread.Sleep(3000);
            string name = form["UserName"];
            if (name.Length >= Constant.ConstValue.UserNameMinLength)
            {
                int i = db.Customers.Count(c => c.UserName == name);
                if (i == 0)
                    return Json(true);
            }
            return Json(false);
        }
    }
}
